package zsc.ruanc.practicaltraining.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import zsc.ruanc.practicaltraining.exception.ApiException;
import zsc.ruanc.practicaltraining.mapper.*;
import zsc.ruanc.practicaltraining.model.domain.*;
import zsc.ruanc.practicaltraining.service.RabbitMQService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private MailboxMapper mailboxMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ReplyMapper replyMapper;


    /**
     *
     * @param fromId 发起者的id
     * @param fromName 发起者的名字
     * @param toId 接收者的id
     * @param ObjectId 文章id | 评论id | 回复id
     * @param type 信息类型
     * @param info 发送的信息
     */
    public void initMailbox(Integer fromId, String fromName, Integer toId, Integer ObjectId, int type, String info) {
        TMailbox vo = new TMailbox();
        vo.setUserId(toId);
        vo.setCreated(new Date());
        vo.setTitle("互动信息");

        if (type == 1) { // 点赞 评论

            TArticle article = articleMapper.getArticle(ObjectId); // 获得文章


            String title = article.getTitle();
            vo.setUserId(article.getUserId());
            vo.setInfo(String.format(info, fromName, String.valueOf(fromId), title, String.valueOf(ObjectId)));

        } else if(type == 2) { // 文章过审核 | 下架
            TArticle article = articleMapper.getArticle(ObjectId); // 获得文章
            vo.setUserId(article.getUserId()); // 收件人
            String title = article.getTitle(); // 文章名
            vo.setTitle("审核信息");
            vo.setInfo(String.format(info, title, String.valueOf(ObjectId)));
        } else if (type == 3) { // 管理员发信息

            // 群发的时候不检查
            if (fromId != null) {
                TUser user = userMapper.selectById(toId);
                // 用户不存在不发送
                if (user == null) {
                    return;
                }
            }

            vo.setTitle("管理员给你的信息");
            vo.setInfo(info);
        } else if (type == 4) { // 对评论点赞

            TComment comment = commentMapper.selectOne(ObjectId);
            String author = comment.getAuthor(); // 获得评论人的名字
            int articleId = comment.getArticleId(); // 获得文章id
            String articleName = articleMapper.getArticleTitle(articleId); // 获得文章标题
            Integer id = userMapper.selectByName(author).getId(); // 获得评论人的id

            String text = String.format(info, fromName, String.valueOf(id), articleName, String.valueOf(articleId), String.valueOf(ObjectId));

            vo.setUserId(id);
            vo.setInfo(text);

        } else if (type == 5) { // 回复
            TReply reply = replyMapper.selectOne(ObjectId); // 查看回复了谁

            TComment comment = commentMapper.selectOne(reply.getCommentId());
            String title = articleMapper.getArticleTitle(comment.getArticleId()); // 查找到文章

            TUser user = userMapper.selectByName(reply.getToName()); // 查找到目标用户

            String text = String.format(info, fromName, String.valueOf(fromId), title, String.valueOf(comment.getArticleId()), String.valueOf(ObjectId));

            vo.setInfo(text);
            vo.setUserId(user.getId());

        } else if (type == 6) { // 回复点赞

            TReply reply = replyMapper.selectOne(ObjectId);
            TUser user = userMapper.selectByName(reply.getToName()); // 找到目标的邮箱

            TComment comment = commentMapper.selectOne(reply.getCommentId());
            String title = articleMapper.getArticleTitle(comment.getArticleId()); // 找到文章id和标题

            String text = String.format(info, fromName, String.valueOf(fromId), title, String.valueOf(comment.getArticleId()), String.valueOf(ObjectId));

            vo.setInfo(text);
            vo.setUserId(user.getId());
        }

        // 发消息
        rabbitTemplate.convertAndSend("fanout_blog", "info", vo);

    }

    // 点赞
    @Override
    @Async
    public void likesMailbox(Integer fromId, String fromName, Integer articleId) {

        String text = "%s(userId:%s) 对你的文章 %s(articleId:%s) 进行了点赞!!!";
        initMailbox(fromId, fromName, null, articleId, 1, text);




    }

    // 评论
    @Override
    @Async
    public void commentMailbox(Integer fromId, String fromName, Integer ObjectId) {
        String text = "%s(userId:%s) 对你的文章 %s(articleId:%s) 进行了评论!!!";
        initMailbox(fromId, fromName, null, ObjectId, 1, text);
    }

    // 回复
    @Override
    @Async
    public void replyMailbox(Integer fromId, String fromName, Integer articleId) {
        String text = "%s(userId:%s) 在文章 %s(articleId:%s) 对你的评论(commentId:%s)进行了回复!!!";
        initMailbox(fromId, fromName, null, articleId, 5, text);
    }

    // 回复点赞
    @Override
    @Async
    public void likesReplyMailbox(Integer fromId, String fromName, Integer replyId) {
        String text = "%s(userId:%s) 在文章 %s(articleId:%s) 对你的回复(replyId:%s)进行了点赞";
        initMailbox(fromId, fromName, null, replyId, 6, text);
    }

    // 文章审核
    @Override
    @Async
    public void verifyMailbox(Integer articleId, Boolean flag) {
        String text = null;
        if (flag == true) {
            text ="炒鸡管理员很喜欢你的文章，你的文章 %s(articleId:%s) 已通过审核";
        } else {
            text ="文章存在违规内容，你的文章 %s(articleId:%s) 已被下架";
        }
        initMailbox(null, null, null, articleId, 2, text);
    }

    // 评论被点赞
    @Override
    @Async
    public void likesCommentMailBox(Integer fromId, String fromName, Integer commentId) {
        String text = "%s(userId:%s) 在文章 %s(article:%s) 对你的评论(commentId:%s) 进行了点赞";
        initMailbox(fromId, fromName, null, commentId, 4, text);
    }




    //----------------------------------------------------------

    // 分页 查看自己信箱信息
    @Override
    public Map select(int cur, int size, int userId) {

        PageHelper.startPage(cur, size).setOrderBy("created desc");
        PageInfo<TMailbox> mailboxPageInfo = new PageInfo<>(this.mailboxMapper.select(userId));

        Map map = new HashMap();
        map.put("total", mailboxPageInfo.getTotal());
        map.put("list", mailboxPageInfo.getList());

        return map;
    }

    // 删除信箱一条信息
    @Override
    public boolean delete(int id, int userId) {

        int x = mailboxMapper.delete(id, userId);

        if (x == 0) {
            throw new ApiException(-1, "请求失败");
        }

        return true;
    }

    // 查看未读信息条数
    @Override
    public int selectUnread(int userId) {

        int x = mailboxMapper.selectUnread(userId);

        return x;
    }

    // 信息标记为已读
    @Override
    public boolean updateFlag(int id, int userId) {

        int x = mailboxMapper.updateFlag(id, userId);

        if (x == 0) {
            throw new ApiException(-1, "请求失败");
        }

        return true;
    }





//-------------------------------管理员-------------------------------
    // 管理员发信息
    @Override
    @Async
    public void adminMailbox(Integer toId, String info) {
        if (toId == null) { // 给所有人发
            List<Integer> list = userMapper.allId();
            for (Integer i : list) {
                initMailbox(null, null, i, null, 3, info);
            }
        } else {
            initMailbox(1, null, toId, null, 3, info);
        }

    }

    //-------------------------------------------------------------------

    // 接收
    @RabbitListener(queues = "fanout_queue_info")
    public void receive(TMailbox vo) {

        // 缓解服务器压力 不要执行的太快
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mailboxMapper.insert(vo);


    }
}
